package com.example.gui;

import static java.sql.DriverManager.println;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HomeActivity extends AppCompatActivity {

    private RecyclerView postRecyclerView;
    private PostAdapter postAdapter;
    private Activity self = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);


        Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(myToolbar);

        // 初始化RecyclerView
        postRecyclerView = findViewById(R.id.postRecyclerView);
        postRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        postAdapter = new PostAdapter(this);
        postRecyclerView.setAdapter(postAdapter);

        // 加载并显示所有帖子
        loadAllPosts();

        //初始化导航栏
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                // 处理每个选项的点击事件
                int itemId = item.getItemId();
                if (itemId == R.id.conversation_list) {
                        // 获取当前显示的 Activity
                        if (self instanceof HomeActivity) {
                            // 已经在主页，不执行跳转操作
                        } else {
                            // 不在主页，执行主页的页面跳转操作
                            Intent intent = new Intent(self, HomeActivity.class);
                            startActivity(intent);
                            overridePendingTransition(0, 0); // 取消Activity转场动画
                        }
                    // 处理对话列表的点击事件，执行相应的页面跳转或页面切换操作
                } else if (itemId == R.id.contact) {
                    String a = "功能未开发";
                    SetMessage(a);
                    // 处理通讯录的点击事件
                } else if (itemId == R.id.setpost) {
                    Intent intent2 = new Intent(HomeActivity.this, SetPostActivity.class);
                    startActivity(intent2);
                    // 处理发帖的点击事件
                } else if (itemId == R.id.discovery) {
                    Intent intent2 = new Intent(HomeActivity.this, ComputerActivity.class);
                    startActivity(intent2);
                    overridePendingTransition(0, 0); // 取消Activity转场动画
                    // 处理小程序的点击事件
                } else if (itemId == R.id.me) {
                    Intent intent2 = new Intent(HomeActivity.this, UserActivity.class);
                    startActivity(intent2);
                    overridePendingTransition(0, 0); // 取消Activity转场动画
                    // 处理我的的点击事件
                }
                return true; // 返回 true 表示消费了该事件，返回 false 则表示未消费
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }//加载menu

    //处理menu点击操作
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // 根据菜单项的ID执行相应的操作
        int itemId = item.getItemId();
        if (itemId == R.id.add_contact) {//加好友
            performAddContact();
            return true;
        } else if (itemId == R.id.scan_qrcode) {//扫码
            performScanQRCode();
            return true;
        }  else if (itemId == R.id.chat) {//群聊
            performChat();
            return true;
        } else if (itemId == R.id.secretChat) {//私聊
            performSecretChat();
            return true;
        } else if (itemId == R.id.author) {
            performAuthor();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    private void performAuthor() {
        //作者
        Intent intent = new Intent(HomeActivity.this, AuthorActivity.class);
        startActivity(intent); // 启动主页
    }

    private void performSecretChat() {
        //私聊
        String a = "功能未开发";
        SetMessage(a);
    }

    private void performChat() {
        //群聊
        String a = "功能未开发";
        SetMessage(a);
    }


    private void performAddContact() {
        // 实现添加朋友的逻辑
        String a = "功能未开发";
        SetMessage(a);

    }

    private void performScanQRCode() {
        // 实现扫描二维码的逻辑
        String a = "功能未开发";
        SetMessage(a);
    }

    private void SetMessage(String ms){
        AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
        builder.setTitle("提示")
                .setMessage(ms)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .create()
                .show();
    }

    private void loadAllPosts() {
        SharedPreferences sharedPreferences = getSharedPreferences("UserData", MODE_PRIVATE);
        Map<String, ?> allPosts = sharedPreferences.getAll();
        List<Post> posts = new ArrayList<>();

        for (String postTitle : allPosts.keySet()) {
            // 获取帖子的内容
            String postContent = sharedPreferences.getString(postTitle, "");

            // 解析帖子的JSON字符串
            try {
                JSONObject postJson = new JSONObject(postContent);

                // 将帖子的标题、内容和头像URL解析出来
                String title = postJson.getString("title");
                String content = postJson.getString("content");
                String avatarUrl = postJson.optString("avatarUrl", "");

                // 创建帖子对象并添加到列表中
                Post post = new Post(title, content, avatarUrl);
                posts.add(post);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        // 设置RecyclerView的数据源
        postAdapter.setPosts(posts);
    }

    private static class PostAdapter extends RecyclerView.Adapter<PostViewHolder> {

        private List<Post> posts;
        private LayoutInflater inflater;

        public PostAdapter(Context context) {
            inflater = LayoutInflater.from(context);
            posts = new ArrayList<>();
        }

        public void setPosts(List<Post> posts) {
            this.posts = posts;
            notifyDataSetChanged();
        }

        @Override
        public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = inflater.inflate(R.layout.item_post, parent, false);
            return new PostViewHolder(view);
        }

        @Override
        public void onBindViewHolder(PostViewHolder holder, int position) {
            Post post = posts.get(position);

            // 设置头像、标题和简介
            holder.avatarImageView.setImageResource(R.drawable.default_avatar);
            holder.titleTextView.setText(post.title);
            holder.introTextView.setText(post.content.substring(0, Math.min(post.content.length(), 50)));
        }

        @Override
        public int getItemCount() {
            return posts.size();
        }
    }

    private static class PostViewHolder extends RecyclerView.ViewHolder {

        public ImageView avatarImageView;
        public TextView titleTextView;
        public TextView introTextView;

        public PostViewHolder(View itemView) {
            super(itemView);

            avatarImageView = itemView.findViewById(R.id.avatarImageView);
            titleTextView = itemView.findViewById(R.id.titleTextView);
            introTextView = itemView.findViewById(R.id.introTextView);

            // 设置点击事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO: 跳转到帖子详情页面
                }
            });
        }
    }

    private static class Post {

        public String title;
        public String content;
        public String avatarUrl;

        public Post(String title, String content, String avatarUrl) {
            this.title = title;
            this.content = content;
            this.avatarUrl = avatarUrl;
        }
    }
}
